// app/model/inventory_adjustment_model.js
'use strict';

module.exports = app => {
  const { STRING, INTEGER, DATE, TEXT, ENUM, DECIMAL } = app.Sequelize;

  const InventoryAdjustment = app.model.define('inventory_adjustment', {
    id: {
      type: INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    organizationId: {
      type: INTEGER,
      allowNull: false,
      field: 'organization_id',
      comment: '组织ID'
    },
    productId: {
      type: INTEGER,
      allowNull: false,
      field: 'product_id',
      comment: '产品ID'
    },
    sku: {
      type: STRING(100),
      allowNull: false,
      comment: '产品SKU'
    },
    productName: {
      type: STRING(200),
      allowNull: false,
      field: 'product_name',
      comment: '产品名称'
    },
    beforeStock: {
      type: INTEGER,
      allowNull: false,
      field: 'before_stock',
      comment: '调整前库存'
    },
    afterStock: {
      type: INTEGER,
      allowNull: false,
      field: 'after_stock',
      comment: '调整后库存'
    },
    adjustQuantity: {
      type: INTEGER,
      allowNull: false,
      field: 'adjust_quantity',
      comment: '调整数量'
    },
    adjustType: {
      type: ENUM('increase', 'decrease', 'set'),
      allowNull: false,
      field: 'adjust_type',
      comment: '调整类型: increase-增加, decrease-减少, set-设置为'
    },
    reason: {
      type: STRING(100),
      allowNull: true,
      comment: '调整原因'
    },
    remark: {
      type: TEXT,
      comment: '备注'
    },
    operatorId: {
      type: INTEGER,
      allowNull: true,
      field: 'operator_id',
      comment: '操作人ID'
    },
    operatorName: {
      type: STRING(100),
      allowNull: true,
      field: 'operator_name',
      comment: '操作人姓名'
    },
    createdAt: {
      type: DATE,
      field: 'created_at'
    },
    updatedAt: {
      type: DATE,
      field: 'updated_at'
    }
  }, {
    tableName: 'inventory_adjustments',
    timestamps: true,
    underscored: true // 使用下划线命名
  });

  // 添加关联关系
  InventoryAdjustment.associate = function() {
    // 库存调整与组织的关联
    if (app.model.OrganizationModel) {
      InventoryAdjustment.belongsTo(app.model.OrganizationModel, {
        foreignKey: 'organizationId',
        as: 'organization'
      });
    }

    // 库存调整与产品的关联
    if (app.model.ProductModel) {
      InventoryAdjustment.belongsTo(app.model.ProductModel, {
        foreignKey: 'productId',
        as: 'product'
      });
    }

    // 库存调整与用户的关联
    if (app.model.UserModel) {
      InventoryAdjustment.belongsTo(app.model.UserModel, {
        foreignKey: 'operatorId',
        as: 'operator'
      });
    }
  };

  return InventoryAdjustment;
};